package exam.demo24;


class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;
    }
}

public class Test1 {
    public boolean IsBalanced_Solution(TreeNode pRoot) {
        // write code here
        if (pRoot == null) {
            return true;
        }
        TreeNode cur = pRoot;
        int leftLen = height(cur.left);
        int rightLen = height(cur.right);
        if (Math.abs(leftLen - rightLen) <= 1) {
            return IsBalanced_Solution(cur.left) && IsBalanced_Solution(cur.right);
        } else {
            return false;
        }
    }

    public int height(TreeNode node) {
        if (node == null) {
            return 0;
        }
        // if(node.left == null && node.right == null) {
        //     return 1;
        // }
        return Math.max(height(node.left), height(node.right)) + 1;
    }
}
